import { useAuthStore } from "../store/auth"

// http 请求 
let base_url = 'https://app.ynsygc.cn'

if (process.env.NODE_ENV === 'development') {
	base_url = 'http://localhost:8080'
}

export const baseUrl = () => {
	return base_url
}

const def_timeout = 10000 // 10秒

const request_token_key = 'Authorization'
const request_rtoken_key = 'RAuthorization'
const request_token_pre = 'Bearer'

// 刷新token
let refreshing = false // 刷新token标志
let tasks = [] // 请求队列

/**
 * 刷新token
 * @param {Object} config 请求参数
 */
const refreshToken = function(config) {
	// 正在刷新
	if (refreshing) return new Promise((resolve, reject) => {
		// 添加到等待队列
		tasks.push({
			ok: () => resolve(request(config)),
			fail: (err) => reject(err)
		})
	})
	// 刷新token
	else {
		refreshing = true
		return new Promise((resolve, reject) => {
			const authStore = useAuthStore()
			authStore.refreshToken().then(() => {
				tasks.forEach(t => t.ok()) // 执行队列
				resolve(request(config)) // 重新发起请求
			}).catch(({ code = -1, message = '无授权' }) => {
				tasks.forEach(t => t.fail({ code, message }))
				reject({ code, message })
			}).finally(() => {
				tasks = [] // 清空队列
				refreshing = false
			})
		})
	}
}

const request = async (config = {}) => {
	// 参数
	const {
		url,
		data,
		header = {},
		method = 'get',
		timeout = def_timeout,
		dataType = 'json',
		hideToken = false, // 不携带token
	} = config

	const authStore = useAuthStore()
	const token = authStore.token

	// 无token，报错
	if (!hideToken && !token) {
		return Promise.reject({ code: -1, message: '授权信息无效' })
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: `${base_url}${url}`,
			data,
			header: {
				...header,
				[request_token_key]: hideToken ? undefined : `${request_token_pre} ${token}`
			},
			method,
			timeout,
			dataType,
			success({ data = {}, statusCode = -1 }) {
				const { code = -1, message = '系统错误', payload = undefined } = data

				// 返回成功的结果
				if (code === 0) {
					resolve(payload)
				}
				// 认证过期，刷新token，重新发起请求
				else if (statusCode === 401 && code === 60010 && config.url.indexOf('/login/refresh') === -1) {
					resolve(refreshToken(config))
				}
				// 错误
				else {
					reject({ code, message })
				}
			},
			fail() {
				reject({ code: -1, message: '系统异常' })
			}
		})
	})
}

/**
 * 使用模块名构建http
 * @param {String} model 模块名
 * @return {uni.request}
 */
export const http = (model) => {
	const m = model
	return (config = {}) => {
		const { url } = config
		if (!url) return Promise.reject({ code: -1, message: '参数错误' })
		// 生产环境增加模块信息
		if (process.env.NODE_ENV !== 'development') {
			config.url = `/$${model}${url}`
		}
		return request(config)
	}
}